package com.getpebble.android.framework.endpoint;

import android.app.KeyguardManager;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PowerManager;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.common.model.PblDeviceModel;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.common.model.PblNotificationModel.Record;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.notification.PblNotificationProcessor;
import com.getpebble.android.framework.notification.PblNotificationProcessor.InvokeActionResult;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService.ActionCallback;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundExtensibleNotificationMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundExtensibleNotificationMessage.InboundAckNack;
import com.getpebble.android.framework.protocol.inbound.PblInboundExtensibleNotificationMessage.InboundNotificationMessageType;
import com.getpebble.android.framework.protocol.outbound.PblOutboundExtensibleNotificationMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundExtensibleNotificationMessage.AttributeType;
import com.getpebble.android.framework.protocol.outbound.PblOutboundExtensibleNotificationMessage.IconId;
import com.getpebble.android.framework.protocol.outbound.PblOutboundExtensibleNotificationMessage.OutboundAckNack;
import com.getpebble.android.framework.protocol.outbound.PblOutboundMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundNotificationMessage;
import com.getpebble.android.framework.util.PebbleCapabilities;
import com.getpebble.android.notifications.PblNotificationService;
import com.getpebble.android.notifications.model.Actions.NotificationDismissKey;
import com.getpebble.android.notifications.model.PblNotification;
import com.getpebble.android.notifications.model.PblNotification.NotificationContent;
import com.getpebble.android.notifications.model.PblNotification.Source;
import com.getpebble.android.notifications.util.CoreNotifications;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.util.concurrent.RateLimiter;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class NotificationEndpoint extends RequestableEndpoint {
    private static final String TAG = NotificationEndpoint.class.getSimpleName();
    private final Context mContext;
    private final boolean mDeviceSupportsExtensibleNotifications;
    private final Handler mHandler;
    private final IEndpointMessageSender mMessageSender;
    private final PowerManager mPowerManager;
    private final PblPreferences mPreferences;
    private final RateLimiter mRateLimiter;
    private final Map<UnsignedInteger, PblOutboundExtensibleNotificationMessage> mSentMessageMap = new HashMap();

    static /* synthetic */ class AnonymousClass4 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction = new int[EndpointAction.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$notification$PblNotificationProcessor$InvokeActionResult = new int[InvokeActionResult.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundExtensibleNotificationMessage$InboundNotificationMessageType = new int[InboundNotificationMessageType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[EndpointAction.SEND_EXTENSIBLE_NOTIFICATION.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[EndpointAction.REMOVE_EXTENSIBLE_NOTIFICATION.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundExtensibleNotificationMessage$InboundNotificationMessageType[InboundNotificationMessageType.INVOKE_ACTION.ordinal()] = 1;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundExtensibleNotificationMessage$InboundNotificationMessageType[InboundNotificationMessageType.ACK_NOTIFICATION.ordinal()] = 2;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$PblNotificationProcessor$InvokeActionResult[InvokeActionResult.REPLIED.ordinal()] = 1;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$PblNotificationProcessor$InvokeActionResult[InvokeActionResult.DEFAULT_ACTION.ordinal()] = 2;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$notification$PblNotificationProcessor$InvokeActionResult[InvokeActionResult.OPENED_ON_PHONE.ordinal()] = 3;
            } catch (NoSuchFieldError e7) {
            }
        }
    }

    public interface INotificationCallback {
        void notificationResult(RequestResult requestResult);
    }

    public static class NotificationEndpointRequest extends EndpointRequest {
        private final INotificationCallback mCallback;
        private final PblNotification mNotification;
        private final UnsignedInteger mNotificationId;

        private NotificationEndpointRequest(PblNotification notification, EndpointAction action, UnsignedInteger notificationId, INotificationCallback callback) {
            super(EndpointId.EXTENSIBLE_NOTIFICATION, action, null);
            this.mNotification = notification;
            this.mNotificationId = notificationId;
            this.mCallback = callback;
        }

        public static NotificationEndpointRequest getAddNotificationRequest(PblNotification notification, UnsignedInteger notificationId, INotificationCallback callback) {
            return new NotificationEndpointRequest(notification, EndpointAction.SEND_EXTENSIBLE_NOTIFICATION, notificationId, callback);
        }

        public static NotificationEndpointRequest getRemoveNotificationRequest(UnsignedInteger notificationId) {
            return new NotificationEndpointRequest(null, EndpointAction.REMOVE_EXTENSIBLE_NOTIFICATION, notificationId, null);
        }

        PblNotification getNotification() {
            return this.mNotification;
        }

        UnsignedInteger getNotificationId() {
            return this.mNotificationId;
        }
    }

    public enum RequestResult {
        FAILED,
        SENT_LEGACY,
        SENT_EXTENSIBLE
    }

    public NotificationEndpoint(IEndpointMessageSender messageSender, Context context) {
        if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender' cannot be null!");
        } else if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        } else {
            this.mContext = context;
            this.mMessageSender = messageSender;
            this.mPreferences = new PblPreferences(context);
            this.mPowerManager = (PowerManager) context.getSystemService("power");
            PblDeviceRecord deviceRecord = PblDeviceModel.getPblDeviceRecord(this.mContext.getContentResolver(), this.mMessageSender.getDevice());
            if (deviceRecord == null || deviceRecord.fwVersion == null) {
                this.mDeviceSupportsExtensibleNotifications = false;
            } else {
                this.mDeviceSupportsExtensibleNotifications = PebbleCapabilities.remoteSupportsExtensibleNotifications(deviceRecord.fwVersion);
            }
            this.mRateLimiter = RateLimiter.create(10.0d);
            HandlerThread thread = new HandlerThread("notifications");
            thread.start();
            this.mHandler = new Handler(thread.getLooper());
        }
    }

    Set<EndpointId> getSupportedEndpoints() {
        return ImmutableSet.of(EndpointId.NOTIFICATION, EndpointId.EXTENSIBLE_NOTIFICATION);
    }

    boolean onReceive(ProtocolMessage message) {
        final PblInboundExtensibleNotificationMessage notificationMessage = new PblInboundExtensibleNotificationMessage(message);
        switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundExtensibleNotificationMessage$InboundNotificationMessageType[notificationMessage.getMessageType().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Trace.debug(TAG, "INVOKE_ACTION message: notificationId = " + notificationMessage.getNotificationId() + " actionId = " + notificationMessage.getActionId());
                PblNotificationProcessor processor = getProcessor();
                if (processor != null) {
                    processor.invokeAction(notificationMessage.getNotificationId(), notificationMessage.getActionId(), notificationMessage.getAttributes(), this.mContext, new ActionCallback() {
                        private Record mRecord;

                        public void result(InvokeActionResult result) {
                            OutboundAckNack ackNack = result == InvokeActionResult.FAILED ? OutboundAckNack.NACK : OutboundAckNack.ACK;
                            PblOutboundExtensibleNotificationMessage response = PblOutboundExtensibleNotificationMessage.getAckNackActionMessage(notificationMessage.getNotificationId(), notificationMessage.getActionId(), ackNack);
                            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$notification$PblNotificationProcessor$InvokeActionResult[result.ordinal()]) {
                                case SMTPMessage.RETURN_FULL /*1*/:
                                    response.addAttribute(AttributeType.SUBTITLE, NotificationEndpoint.this.mContext.getString(R.string.action_sent));
                                    Integer titleKey = Integer.valueOf(1);
                                    String title = notificationMessage.getAttributes().containsKey(titleKey) ? (String) notificationMessage.getAttributes().get(titleKey) : null;
                                    if (title == null || title.codePointCount(0, title.length()) != 1) {
                                        if (this.mRecord != null && NotificationEndpoint.this.isMailPackage(this.mRecord.androidPackageName)) {
                                            response.addAttribute(AttributeType.SMALL_ICON, IconId.SENT_MAIL.getId());
                                            break;
                                        } else {
                                            response.addAttribute(AttributeType.SMALL_ICON, IconId.SENT_MESSAGE.getId());
                                            break;
                                        }
                                    }
                                    response.addAttribute(AttributeType.TITLE, title);
                                    break;
                                    break;
                                case SMTPMessage.RETURN_HDRS /*2*/:
                                    response.addAttribute(AttributeType.SUBTITLE, NotificationEndpoint.this.mContext.getString(R.string.action_done));
                                    break;
                                case ListInfo.INDETERMINATE /*3*/:
                                    response.addAttribute(AttributeType.SUBTITLE, NotificationEndpoint.this.mContext.getString(R.string.action_opened_on_phone));
                                    response.addAttribute(AttributeType.LARGE_ICON, IconId.PHONE_CHECKMARK.getId());
                                    break;
                            }
                            if (!(this.mRecord == null || result == InvokeActionResult.FAILED || VERSION.SDK_INT < 18)) {
                                PblNotificationService.dismissNotification(NotificationDismissKey.from(this.mRecord));
                            }
                            Trace.debug(NotificationEndpoint.TAG, "Sending " + ackNack + " to watch (sent = " + NotificationEndpoint.this.mMessageSender.sendMessage(response) + ")");
                        }

                        public void setNotificationRecord(Record record) {
                            this.mRecord = record;
                        }
                    });
                    break;
                }
                Trace.warning(TAG, "processor is null");
                break;
            case SMTPMessage.RETURN_HDRS /*2*/:
                UnsignedInteger nextAvailableId = notificationMessage.getNextAvailableId();
                final UnsignedInteger incomingId = notificationMessage.getNotificationId();
                InboundAckNack ackNack = notificationMessage.getAckNack();
                Trace.debug(TAG, "ACK_NOTIFICATION message: notificationId = " + incomingId + " res = " + ackNack + " nextAvailableId = " + nextAvailableId);
                if (!InboundAckNack.ACK.equals(ackNack)) {
                    Trace.debug(TAG, "Notification not ACKed: tell notification processor");
                    final PblNotificationProcessor notifProcessor = getProcessor();
                    if (notifProcessor == null) {
                        Trace.warning(TAG, "processor is null");
                    } else if (InboundAckNack.NACK_NOTIFICATION_ID_COLLISION.equals(ackNack) || InboundAckNack.NACK_RETRY_NOTIFICATION.equals(ackNack)) {
                        PblOutboundExtensibleNotificationMessage retryMessage = (PblOutboundExtensibleNotificationMessage) this.mSentMessageMap.get(incomingId);
                        if (retryMessage != null) {
                            if (!InboundAckNack.NACK_NOTIFICATION_ID_COLLISION.equals(ackNack)) {
                                Trace.verbose(TAG, "Retrying notification send to watch for " + ackNack + ". id = " + retryMessage.getNotificationID());
                            } else if (nextAvailableId != null) {
                                Trace.verbose(TAG, "Retrying notification send to watch for " + ackNack + ". Old id = " + retryMessage.getNotificationID() + " new id = " + nextAvailableId);
                                PblNotificationProcessor.setLastNotificationId(nextAvailableId, new PblPreferences(PebbleApplication.getAppContext()));
                                retryMessage.changeNotificationId(nextAvailableId);
                            } else {
                                Trace.verbose(TAG, "Not retrying for collision where no new ID was specified");
                                retryMessage = null;
                            }
                        }
                        if (retryMessage == null) {
                            Trace.debug(TAG, "retryMessage is null");
                            notifProcessor.handleNotificationNack(incomingId);
                        } else {
                            final PblOutboundExtensibleNotificationMessage messageToSend = retryMessage;
                            this.mHandler.postDelayed(new Runnable() {
                                public void run() {
                                    Trace.verbose(NotificationEndpoint.TAG, "Delayed notification retry...");
                                    notifProcessor.reassignActions(incomingId, messageToSend.getNotificationID());
                                    NotificationEndpoint.this.sendMessage(messageToSend, null, null, messageToSend.getNotificationID());
                                }
                            }, 200);
                        }
                    } else {
                        notifProcessor.handleNotificationNack(notificationMessage.getNotificationId());
                    }
                }
                this.mSentMessageMap.remove(notificationMessage.getNotificationId());
                break;
        }
        return true;
    }

    protected PblNotificationProcessor getProcessor() {
        return PblNotificationProcessor.getInstance();
    }

    boolean onRequest(EndpointRequest request, FrameworkState frameworkState) {
        Trace.debug(TAG, "Got request");
        if (request instanceof NotificationEndpointRequest) {
            NotificationEndpointRequest notificationRequest = (NotificationEndpointRequest) request;
            switch (AnonymousClass4.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    PblNotification notification = notificationRequest.getNotification();
                    if (notification == null) {
                        notificationRequest.mCallback.notificationResult(RequestResult.FAILED);
                        return true;
                    }
                    boolean isDemoNotification = notification.getSource().equals(Source.DEMO);
                    boolean locked = ((KeyguardManager) this.mContext.getSystemService("keyguard")).isKeyguardLocked();
                    if (!isDemoNotification && !this.mPreferences.getBooleanData(PrefKey.ALWAYS_NOTIFY, true) && !locked && this.mPowerManager.isScreenOn()) {
                        Trace.debug(TAG, "Screen is on and unlocked; not sending notification");
                        notificationRequest.mCallback.notificationResult(RequestResult.FAILED);
                        return true;
                    } else if (this.mDeviceSupportsExtensibleNotifications) {
                        sendUsingExtensibleProtocol(notificationRequest);
                        return true;
                    } else {
                        sendUsingOldNotificationProtocol(notificationRequest);
                        return true;
                    }
                case SMTPMessage.RETURN_HDRS /*2*/:
                    if (!this.mDeviceSupportsExtensibleNotifications) {
                        return true;
                    }
                    this.mMessageSender.sendMessage(PblOutboundExtensibleNotificationMessage.getRemoveNotificationMessage(notificationRequest.getNotificationId()));
                    return true;
                default:
                    return true;
            }
        }
        Trace.warning(TAG, "Invalid request; not NotificationEndpointRequest");
        return false;
    }

    private void sendMessage(PblOutboundMessage message, INotificationCallback callback, RequestResult successMode, UnsignedInteger notificationId) {
        final PblOutboundMessage pblOutboundMessage = message;
        final RequestResult requestResult = successMode;
        final UnsignedInteger unsignedInteger = notificationId;
        final INotificationCallback iNotificationCallback = callback;
        this.mHandler.post(new Runnable() {
            public void run() {
                NotificationEndpoint.this.mRateLimiter.acquire();
                Trace.verbose(NotificationEndpoint.TAG, "Got rate limiter - sending message");
                boolean sent = NotificationEndpoint.this.mMessageSender.sendMessage(pblOutboundMessage);
                if (sent && requestResult != null && requestResult.equals(RequestResult.SENT_EXTENSIBLE) && unsignedInteger != null && (pblOutboundMessage instanceof PblOutboundExtensibleNotificationMessage)) {
                    NotificationEndpoint.this.mSentMessageMap.put(unsignedInteger, pblOutboundMessage);
                }
                if (iNotificationCallback != null) {
                    iNotificationCallback.notificationResult(sent ? requestResult : RequestResult.FAILED);
                }
            }
        });
    }

    boolean onPrfRequest(EndpointRequest request, FrameworkState frameworkState) {
        return true;
    }

    private boolean isMailPackage(String packageName) {
        if (packageName == null) {
            return false;
        }
        for (String emailPackageName : CoreNotifications.EMAIL_PACKAGE_NAMES) {
            if (emailPackageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    private void sendUsingExtensibleProtocol(NotificationEndpointRequest request) {
        Trace.debug(TAG, "sendUsingExtensibleProtocol: id = " + request.mNotificationId);
        sendMessage(PblOutboundExtensibleNotificationMessage.getAddNotificationMessage(request.getNotification(), request.getNotificationId()), request.mCallback, RequestResult.SENT_EXTENSIBLE, request.getNotificationId());
    }

    private void sendUsingOldNotificationProtocol(NotificationEndpointRequest request) {
        Trace.debug(TAG, "sendUsingOldNotificationProtocol: id = " + request.mNotificationId);
        NotificationContent content = request.getNotification().getNotificationContent();
        sendMessage(PblOutboundNotificationMessage.createSmsNotification(content.notificationTitle, content.notificationBody, String.valueOf(request.getNotification().getPostTimeLocalMillis())), request.mCallback, RequestResult.SENT_LEGACY, null);
    }
}
